<template>
  <div class="musicDetailCard" :class="musicCardIsShow ? '' : 'isShow'">
    <div class="isShowBtn" @click="isShow">
      <i
        class="el-icon-arrow-down"
        :class="{ fontColor: songMv.length > 0 }"
      ></i>
    </div>
    <div
      class="body"
      v-if="musicInfo.ar"
      :class="{ fontColor: videoUrl.length > 0 }"
    >
      <div class="top">
        <div class="left">
          <img
            src="@/assets/img/MusicDetailCard/needle.png"
            alt=""
            class="play"
            :class="$store.state.isPlay ? 'zhuan' : ''"
          />
          <!-- <div class="play" :class="$store.state.isPlay ? 'zhuan' : ''"></div> -->
          <div
            class="disc"
            :class="$store.state.isPlay ? 'rotate' : 'playState rotate'"
          >
            <img class="cd" src="@/assets/img/MusicDetailCard/disc.png" />
            <img :src="musicInfo.al.picUrl" alt="" class="musicItem" />
          </div>
        </div>
        <div class="right">
          <div class="music">
            <div class="musicName">{{ musicInfo?.name }}</div>
            <div class="musicInfo" :class="{ fontColor: videoUrl.length > 0 }">
              <div class="name">{{ musicInfo?.name }}</div>
              <div class="author">{{ musicInfo?.ar[0].name }}</div>
            </div>
          </div>
          <div class="lyric">
            <lyricPage :lyric="lyric" :openMv="videoUrl.length > 0"></lyricPage>
          </div>
        </div>
      </div>
      <div class="comment">
        <comment
          v-if="currentCommentPage == 1"
          :commentType="'music'"
          :comments="hotComments"
          :commentId="this.$store.state.musicId + ''"
          :musicTitle="musicInfo.name"
          :openMv="videoUrl.length > 0 ? true : false"
          @getComment="handleGetComment"
          ref="hotComment"
          @handleBacktop="handleBacktop"
          ><p slot="title">精彩评论</p></comment
        >
        <comment
          :commentType="'music'"
          :comments="comment.comments"
          :commentId="this.$store.state.musicId + ''"
          :musicTitle="musicInfo.name"
          :openMv="videoUrl.length > 0 ? true : false"
          @getComment="handleGetComment"
          ref="Comment"
          @handleBacktop="handleBacktop"
          ><p slot="title">最新评论</p></comment
        >
        <div class="pagination">
          <el-pagination
            background
            layout="prev,pager,next"
            :total="comment.total"
            :page-size="20"
            :current-page="currentCommentPage"
            @current-change="commentPageChange"
            hide-on-single-page
          >
          </el-pagination>
          <el-backtop ref="boxScroll" target=".musicDetailCard"></el-backtop>
        </div>
      </div>
      <button
        class="background"
        @click="openBjMv"
        :style="{ top: !musicCardIsShow ? '1000px' : '' }"
        :class="{ red: openBtnHtml === '开启背景Mv' }"
      >
        {{ openBtnHtml }}
      </button>
    </div>
    <div class="none" v-else>暂无播放音乐</div>
    <div class="mv" v-if="videoUrl">
      <video :src="videoUrl" autoplay ref="audioPlayer" muted></video>
    </div>
  </div>
</template>
<script>
import lyricPage from './lyricPage.vue'
import {
  getLyric,
  getMusicComment,
  getMusicHotComment
} from '@/api/musicCard/musicCard'
import { getMvUrl } from '@/api/discover/singerDetail'
import comment from '@/views/musicDetail/components/comment.vue'
import { getSingerMvDetail } from '@/api/discover/singerDetail'
export default {
  data() {
    return {
      // 是否显示
      musicCardIsShow: false,
      // 歌曲详细信息
      musicDetail: {},
      // 卡片显示状态
      musicCardType: false,
      //   当前歌曲信息
      musicInfo: {},
      //   歌词
      lyric: [[0, '正在加载歌词']],
      // 定时器
      timer: null,
      // 是否删除卡片渲染的内容
      cleanCard: true,
      // 热门评论
      hotComments: [],
      // 评论数据
      comment: {},
      // 评论是否在加载中
      isCommentLoading: false,
      //当前评论页数
      currentCommentPage: 1,
      // 当前播放歌曲的歌手id
      singerId: '',
      // 歌曲名称
      songName: '',
      // mv页数
      videoPage: 1,
      // 歌手mv数据
      singerMvInfo: { mvs: [], hasMore: false },
      // 是否找到对应mv
      isFind: false,
      // 找到的Mv
      songMv: {},
      // 保存mv
      saveMv: {},
      // mv视频 地址
      videoUrl: '',
      saveUrl: '',
      // 按钮内容
      openBtnHtml: '无背景Mv'
    }
  },
  components: {
    lyricPage,
    comment
  },
  methods: {
    // 开启音乐卡片
    isShow() {
      // this.musicCardType = false
      // 清除背景mv
      this.$store.commit('updateMusicCardMv', '')
      this.$store.commit('updateMusicIsshow', false)
    },
    // 获取歌词并处理
    async getLyric(id) {
      const res = await getLyric(id)
      let lyric = res.data.lrc.lyric
      // 一换行转成数组
      let arr = lyric.split('\n')
      // 保存转换后的数组
      let Array = []
      // 需要处理的带括号的时间
      let time = ''
      // 处理好的歌词
      let value = ''
      // 最后的结果数组【时间，对应的歌词】
      let result = []

      arr.forEach((item) => {
        if (item !== '') {
          Array.push(item)
        }
      })
      Array.forEach((item) => {
        time = item.split(']')[0] // '[00:00.00'
        value = item.split(']')[1] // '作词 ： xxx'
        const t = time.slice(1).split(':') // [分，秒.毫秒]
        result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]) // 【分乘60秒 + 秒.毫秒取整，歌词】
      })
      this.lyric = result
      // console.log(this.lyric)
    },
    // 获取评论
    async getMusicComment(id) {
      // console.log(id)
      // 获取时间戳
      var timestamp = Date.parse(new Date())

      this.isCommentLoading = true

      // 当页数为第一页时，请求10条热门数据
      if (this.currentCommentPage == 1) {
        let res = await getMusicHotComment({
          id,
          limit: 10,
          type: 0,
          timestamp
        })
        if (res.data.code != 200) {
          this.$message.error('获取热门评论失败,请稍后重试!')
          return
        }
        this.hotComments = res.data.hotComments
        // console.log(this.hotComments, '热门')
      }

      let res = await getMusicComment({
        id,
        offset: (this.currentCommentPage - 1) * 20,
        timestamp
      })
      if (res.data.code !== 200) {
        this.$message.error('获取评论失败,请稍后重试!')
      }

      this.isCommentLoading = false
      this.comment = res.data
      // console.log(this.comment, '评论')
    },
    // 发布评论和点赞后的回调
    handleGetComment() {
      console.log('发布，点赞后刷新评论')
      this.getMusicComment(this.$store.state.musicId)
    },
    // 下一页
    // 分页页数更新
    commentPageChange(page) {
      // 回到顶部
      this.handleBacktop()
      this.currentCommentPage = page
      this.getMusicComment(this.$store.state.musicId)
    },
    // 点击评论的评论回到置顶
    handleBacktop() {
      const dom = document.querySelector('.comment')
      dom.querySelector('.el-backtop').click()
    },
    // 获取歌手mv列表
    async getSingerMvList() {
      const res = await getSingerMvDetail({
        id: this.singerId,
        limit: 20 * this.videoPage
      })
      // console.log(res)
      this.singerMvInfo = res.data
      // console.log(this.singerMvInfo, 'mv列表')
      await this.getMusicNameInTheMv()
      if (this.songMv.length > 0) await this.getMvUrl()
    },
    // 筛选mv名字和歌曲名字是否有相同
    getMusicNameInTheMv() {
      let arr = []
      this.singerMvInfo.mvs.forEach((item) => {
        // console.log(item.name, this.songName)
        if (item.name.indexOf(this.songName) != -1) {
          arr.push(item)
          this.isFind = true
        }
      })
      // 没找到并且mv大于20条
      if (!this.isFind && this.singerMvInfo.mvs.length > 20) {
        this.videoPage += 1
        this.getSingerMvList()
      }
      // console.log(arr, '对应的Mv列表')
      if (arr.length <= 0) {
        // this.$message.warning('没有对应Mv')
        this.openBtnHtml = '没有背景Mv'
      }
      this.songMv = arr
      this.saveMv = this.songMv
    },
    // 获取mv地址
    async getMvUrl() {
      const res = await getMvUrl({
        id: this.songMv[0].id
      })
      this.saveUrl = res.data.data.url
      if (this.saveUrl.length > 0) {
        this.openBtnHtml = '开启背景Mv'
      }
      // console.log(this.videoUrl, 'mv地址')
    },
    // 点击开启背景Mv
    async openBjMv() {
      if (this.videoUrl.length > 0) {
        this.songMv = {}
        this.videoUrl = ''
        return
      }
      // console.log(!!this.songMv.length)
      if (!this.saveUrl.length) {
        this.$message.warning('没找到对应Mv')
        // this.openBtnHtml = '没有背景Mv'
      }
      // await this.getSingerMvList()
      if (this.saveUrl) {
        this.videoUrl = this.saveUrl
        this.$store.commit('updateMusicCardMv', this.videoUrl)
        this.songMv = this.saveMv
        return
      }
    }
  },
  watch: {
    '$store.state.CardMv'(changeValue) {
      console.log(changeValue, '开关状态')
      if (changeValue === '') {
        this.videoUrl = ''
        this.songMv = {}
      }
    },
    '$store.state.musicisShow'(changeValue) {
      if (
        changeValue === true &&
        !(this.videoUrl.length > 0) &&
        this.$store.state.musicId.length > 0
      ) {
        // console.log(changeValue, this.videoUrl.length)
        this.getSingerMvList()
      }
      this.musicCardIsShow = changeValue
      // console.log(this.musicCardIsShow)
      clearTimeout(this.timer)
      this.cleanCard = false
      if (
        this.musicCardIsShow &&
        // !this.comment.comments &&
        this.$store.state.musicId != ''
      ) {
        // console.log('请求歌词和评论')
        this.getLyric(this.$store.state.musicId)
        this.getMusicComment(this.$store.state.musicId)
      }
      //   当卡片关闭时 延迟 3s再删除里面渲染的内容 提升体验
      else if (this.musicCardIsShow == false) {
        this.$store.commit('updateMusicCardMv', '')
        this.timer = setTimeout(() => {
          this.cleanCard = true
        }, 3000)
      }
    },
    // 监视音乐id变化了说明变化了
    '$store.state.musicId'() {
      this.videoUrl = ''
      this.saveUrl = ''
      this.songMv = {}
      // console.log(musicId)
      this.getLyric(this.$store.state.musicId)
      this.getMusicComment(this.$store.state.musicId)
      this.musicInfo =
        this.$store.state.musicList[this.$store.state.currentIndex]
      // console.log(this.musicInfo, '播放的歌曲信息')
      // 获取播放歌曲的歌手id
      this.singerId = this.musicInfo.ar[0].id
      this.songName = this.musicInfo.name
      if (!this.videoUrl.length > 0) {
        console.log(12312312412412)
        this.getSingerMvList()
      }
    },
    videoUrl() {
      // console.log('mv地址变化')
      let time = setTimeout(() => {
        this.$refs.audioPlayer.volume = 0
      }, 100)

      this.$nextTick(() => {
        if (!this.$refs.audioPlayer) {
          clearTimeout(time)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.musicDetailCard {
  position: fixed;
  top: 0;
  width: 100%;
  height: calc(100vh - 60px);
  background: linear-gradient(to bottom, #e3e2e3, #fff);
  z-index: 998; // 比playe低 999
  transition: all 0.6s ease;
  // overflow-y: scroll;
  overflow: auto;
  overflow-x: hidden;
}
.isShow {
  top: calc(100vh);
  // top: 0;
}
.isShowBtn {
  position: relative;
  top: 20px;
  left: 30px;
  .el-icon-arrow-down {
    font-size: 30px;
    cursor: pointer;
  }
}
.none {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  color: #666;
}
.body {
  display: flex;
  flex-direction: column;
  align-items: center;
  .top {
    display: flex;
    // background-color: #666;
    // margin-bottom: 150px;
    .left {
      width: 45%;
      position: relative;
      margin-right: 15px;
      .disc {
        position: relative;
        width: 280px;
        height: 280px;
        margin-right: 150px;
        margin-top: 150px;
      }
      .cd {
        text-align: center;
        width: 280px;
        height: 280px;
        border-radius: 50%;
        // background-color: pink;
      }
      .musicItem {
        width: 190px;
        height: 190px;
        position: absolute;
        top: 45px;
        left: 45px;
        z-index: -1;
      }
      .play {
        width: 150px;
        // height: 10px;
        // background-color: skyblue;
        position: absolute;
        top: 80px;
        left: 130px;
        transform: rotate(-15deg);
        transform-origin: left top;
        transition: all 1s ease;
        z-index: 10;
      }
    }
    .right {
      width: 350px;
      display: flex;
      flex-direction: column;
      align-items: center;
      .music {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        .musicName {
          font-size: 25px;
          margin-top: 20px;
        }
        .musicInfo {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          color: #666;
          .name {
            margin: 4px 0;
          }
        }
      }
      .lyric {
        width: 150%;
        height: 330px;
        // padding-top: 30px;
        // background-color: aquamarine;
      }
    }
  }
  .comment {
    width: 1000px;
    margin-top: 80px;
    // background-color: skyblue;
  }
}
.zhuan {
  transform: rotate(15deg) !important;
}
// 碟子无线转动
.rotate {
  animation: everRotate 25s linear infinite;
  animation-delay: 1s; // 延迟一秒和play一致
}
@keyframes everRotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
// 暂停动画
.playState {
  animation-play-state: paused;
}
// 分页
.pagination {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
}

.background {
  position: fixed;
  top: 800px;
  right: 50px;
  padding: 10px 15px;
  border-radius: 15px;
  border: none;
  color: #666;
  font-size: 16px;
  transition: all 1s;
  cursor: pointer;
  &:hover {
    background-color: #e1e1e1;
  }
}
// 背景mv
.mv {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  // display: flex;
  // justify-content: center;
  video {
    // 有些背景音乐尺寸不同强制铺满会显示有问题-待解决
    // 思路 手机竖屏拍的居中，左右两边加背景毛玻璃
    // 正常铺满的就不管
    min-width: 100%;
    min-height: 100%;
  }
}
.fontColor {
  color: #fff !important;
}
// 背景按钮有mv时
.red {
  background-color: #f55252;
  color: #fff;
  &:hover {
    background-color: #e91e1e !important;
  }
}
</style>
